<template>
  <el-dialog title="上传作品" :visible.sync="visible" @close="close()">
    <el-form
      v-loading="pageLoading"
      element-loading-text="上传中..."
      ref="dataForm"
      :rules="dataRule"
      :model="dataForm"
      label-position="right"
      label-width="80px"
    >
      <!-- 作品类型 -->
      <el-form-item label="作品类型" prop="workType">
        <el-radio v-model="dataForm.workType" label="图片">图片</el-radio>
        <el-radio v-model="dataForm.workType" label="视频">视频</el-radio>
      </el-form-item>
      <div>
        <div>
          <div class="btn" v-if="dataForm.workType == '图片'">
            <el-button type="primary" icon="el-icon-upload" @click="chooseImage"
              >选择图片</el-button
            >
            <input
              type="file"
              ref="imageInput"
              multiple
              accept="image/*"
              style="display: none"
              @change="handleImageUpload"
            />
          </div>
          <div class="btn" v-if="dataForm.workType == '视频'">
            <el-button type="primary" icon="el-icon-upload" @click="chooseVideo"
              >选择视频</el-button
            >
            <input
              type="file"
              ref="videoInput"
              name="file"
              id="file"
              multiple
              accept="video/*"
              style="display: none"
              @change="handleFileChange"
            />
          </div>
        </div>
        <div class="imgvideo">
          <div v-for="(file, index) in uploadedFiles" :key="index">
            <div class="listss">
              <img
                v-if="file.type === 'image'"
                :src="file.url"
                :alt="file.file.name"
                width="100"
                height="100"
              />
              <video
                v-else
                :src="file.url"
                :controls="true"
                width="100"
                height="100"
              ></video>
              <!-- <i style="display: block;" @click="removeFile(index)" class="el-icon-delete-solid"></i> -->
              <!-- <p>{{ file.file.name }}</p> -->
            </div>
          </div>
        </div>
      </div>
      <!-- 封面方向 -->
      <el-form-item label="封面方向" v-if="dataForm.workType == '视频'">
        <el-radio v-model="aaa" label="纵向封面">纵向封面</el-radio>
        <el-radio v-model="aaa" label="横向封面">横向封面</el-radio>
      </el-form-item>
      <!-- 纵向作品封面 -->
      <div>
        <div
          class="btn"
          v-if="dataForm.workType == '视频' && aaa == '纵向封面'"
        >
          <el-button type="primary" icon="el-icon-upload" @click="chooseImagez"
            >选择纵向封面</el-button
          >
          <input
            type="file"
            ref="imageInputz"
            accept="image/*"
            style="display: none"
            @change="handleImageUploadz"
          />
        </div>
        <div
          class="btn"
          v-if="dataForm.workType == '视频' && aaa == '横向封面'"
        >
          <el-button type="primary" icon="el-icon-upload" @click="chooseImagew"
            >选择横向封面</el-button
          >
          <input
            type="file"
            ref="imageInputw"
            accept="image/*"
            style="display: none"
            @change="handleImageUploadw"
          />
        </div>
      </div>
      <div class="imgvideo">
        <div
          class="listss"
          v-if="dataForm.workType == '视频' && aaa == '纵向封面'"
        >
          <img
            v-if="imageUrlzurl"
            :src="imageUrlzurl"
            :alt="imageUrlzurl"
            width="100"
            height="100"
          />
          <!-- <i style="display: block;" @click="removeFile(index)" class="el-icon-delete-solid"></i> -->
          <!-- <p>{{ file.file.name }}</p> -->
        </div>
        <div
          class="listss"
          v-if="dataForm.workType == '视频' && aaa == '横向封面'"
        >
          <img
            v-if="imageUrlwurl"
            :src="imageUrlwurl"
            :alt="imageUrlwurl"
            width="100"
            height="100"
          />
          <!-- <i style="display: block;" @click="removeFile(index)" class="el-icon-delete-solid"></i> -->
          <!-- <p>{{ file.file.name }}</p> -->
        </div>
      </div>

      <!-- 作品标题 -->
      <el-form-item label="作品标题" prop="workTitle">
        <el-input v-model="dataForm.workTitle" />
      </el-form-item>
      <!-- 作品简介 -->
      <el-form-item label="作品简介" prop="workDescr">
        <el-input v-model="dataForm.workDescr" />
      </el-form-item>
      <!-- 选择角色 -->
      <el-form-item label="作品分类" prop="workCategoryId">
        <el-select
          v-model="dataForm.workCategoryId"
          placeholder="请选择"
          style="width: 60%"
        >
          <el-option
            v-for="item in roleOpts"
            :key="item.workCategoryId"
            :label="item.workCategoryName"
            :value="item.workCategoryId"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancell()">
        {{ $t("table.cancel") }}
      </el-button>
      <el-button type="primary" @click="dataFormSubmit()">
        {{ $t("table.confirm") }}
      </el-button>
    </div>
  </el-dialog>
</template>

<script type="text/javascript" src="./js/jquery.js" th:src="@{/js/jquery.js}"></script>
<script type="text/javascript" src="./js/spark-md5.min.js" th:src="@{/js/spark-md5.min.js}"></script>
<script type="text/javascript" src="./js/base.js" th:src="@{/js/base.js}"></script>
<script>
import * as api from "@/api/multishop/shop-user";
import SparkMD5 from "spark-md5";
export default {
  data() {
    return {
      aaa: "",
      pageLoading: false,
      imageFile: "",
      imageUrlzurl: "",
      imageUrlwurl: "",
      videoFile: "",
      uploadedFiles: [],
      formData: new FormData(),
      visible: false,
      dataForm: {
        workTitle: "",
        workDescr: "",
        workCategoryId: "",
        pageType: 0,
      },
      roleOpts: [],
      dataRule: {
        workTitle: [
          { required: true, message: "作品标题不能为空", trigger: "blur" },
        ],
        workDescr: [
          { required: true, message: "作品简介不能为空", trigger: "blur" },
        ],
        workCategoryId: [
          { required: true, message: "请选择作品分类", trigger: "blur" },
        ],
      },
    };
  },
  mounted() {
    this.getlist();
  },
  methods: {
    close() {
      this.visible = false;
      this.dataForm = {};
      this.formData = new FormData();
      this.imageFile = {};
      this.videoFile = {};
      this.uploadedFiles = [];
      this.dataForm.workCoverUrl = null;
      this.dataForm.xworkCoverUrl = null;
      this.imageUrlzurl = null;
      this.imageUrlwurl = null;
    },
    chooseImagez() {
      const imageInputz = this.$refs.imageInputz;
      imageInputz.click();
    },
    handleImageUploadz(event) {
      // 获取上传的文件
      const file = event.target.files[0];
      // 创建一个 URL 对象来获取图片地址
      this.imageUrlzurl = URL.createObjectURL(file);
      const zdata = new FormData();
      zdata.append("file", file);
      api.upload_minio(zdata).then((pageVO) => {
        console.log("zzzzzzzzzzzdata");
        console.log(pageVO);
        this.dataForm.workCoverUrl = pageVO.showUrls[0];

        console.log("zzzzzzzzzzzdata");
      });
    },
    chooseImagew() {
      const imageInputw = this.$refs.imageInputw;
      imageInputw.click();
    },
    handleImageUploadw(event) {
      // 获取上传的文件
      const file = event.target.files[0];
      // 创建一个 URL 对象来获取图片地址
      this.imageUrlwurl = URL.createObjectURL(file);
      const wdata = new FormData();
      wdata.append("file", file);
      api.upload_minio(wdata).then((pageVO) => {
        console.log("zzzzzzzzzzzdata");
        console.log(pageVO);
        this.dataForm.xworkCoverUrl = pageVO.showUrls[0];
        console.log("zzzzzzzzzzzdata");
      });
    },
    chooseImage() {
      const imageInput = this.$refs.imageInput;
      imageInput.click();
    },
    chooseVideo() {
      const videoInput = this.$refs.videoInput;
      videoInput.click();
    },
    handleImageUpload() {
      if (this.videoFile) {
        this.$message.error("不能再上传图片了！");
      } else {
        const imageInput = this.$refs.imageInput;
        const imageFiles = imageInput.files;

        for (let i = 0; i < imageFiles.length; i++) {
          this.imageFile = imageFiles[i];
          const imageUrl = window.URL.createObjectURL(this.imageFile);

          // 添加图片文件到uploadedFiles数组
          this.uploadedFiles.push({
            file: this.imageFile,
            url: imageUrl,
            type: "image", // 用于标识文件类型
          });

          // 添加图片文件到formData对象（如果需要上传到服务器）
          this.formData.append("file", this.imageFile);
        }

        // 清空文件输入框
        imageInput.value = "";
      }
    },
    // handleFileChange() {
    //     if (this.imageFile) {
    //         this.$message.error('不能再上传视频了！');
    //     } else {
    //         const videoInput = this.$refs.videoInput;
    //         const videoFiles = videoInput.files;

    //         for (let i = 0; i < videoFiles.length; i++) {
    //             this.videoFile = videoFiles[i];
    //             const videoUrl = window.URL.createObjectURL(this.videoFile);

    //             // 添加视频文件到uploadedFiles数组
    //             this.uploadedFiles.push({
    //                 file: this.videoFile,
    //                 url: videoUrl,
    //                 type: 'video', // 用于标识文件类型
    //             });

    //             // 添加视频文件到formData对象（如果需要上传到服务器）
    //             this.formData.append('file', this.videoFile);
    //         }

    //         // 清空文件输入框
    //         videoInput.value = '';
    //     }

    // },
    handleFileChange(event) {
      let file = event.target.files[0];
      this.calculateFileMd5ByDefaultChunkSize(file).then((md5) => {
        let formData = new FormData();
        formData.append("md5", md5);
        formData.append("file", file);
        this.checkMd5(md5, file);
      });
    },
    calculateFileMd5(file, chunkSize) {
      return new Promise((resolve, reject) => {
        let blobSlice =
          File.prototype.slice ||
          File.prototype.mozSlice ||
          File.prototype.webkitSlice;
        let chunks = Math.ceil(file.size / chunkSize);
        let currentChunk = 0;
        let spark = new SparkMD5.ArrayBuffer();
        let fileReader = new FileReader();

        fileReader.onload = function (e) {
          spark.append(e.target.result);
          currentChunk++;
          if (currentChunk < chunks) {
            loadNext();
          } else {
            let md5 = spark.end();
            resolve(md5);
          }
        };

        fileReader.onerror = function (e) {
          reject(e);
        };

        function loadNext() {
          let start = currentChunk * chunkSize;
          let end = start + chunkSize;
          if (end > file.size) {
            end = file.size;
          }
          fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
        }

        loadNext();
      });
    },
    calculateFileMd5ByDefaultChunkSize(file) {
      return this.calculateFileMd5(file, 2097152);
    },
    checkMd5(md5, file) {
      api
        .Fcheck({
          md5: md5,
        })
        .then((response) => {
          console.log(response.status);
          if (response.status === 20000) {
            this.$message({
              message: "文件已经存在，无需上传",
              type: "warning",
            });
          } else if (response.status === 40004) {
            // 添加视频文件到uploadedFiles数组
            const videoUrl = window.URL.createObjectURL(file);
            this.uploadedFiles.push({
              file: file,
              url: videoUrl,
              type: "video", // 用于标识文件类型
            });

            // 添加视频文件到formData对象（如果需要上传到服务器）
            this.formData.append("file", file);
            console.log("文件不存在，需要上传");
            this.postFile(file, 0, md5);
          } else {
            console.log("未知错误");
          }
        });
    },
    postFile(file, i, md5) {
      let name = file.name;
      let size = file.size;
      let shardSize = 5 * 1024 * 1024;
      let shardCount = Math.ceil(size / shardSize);
      if (i >= shardCount) {
        return;
      }

      let start = i * shardSize;
      let end = start + shardSize;
      let packet = file.slice(start, end);
      let formData = new FormData();
      formData.append("md5", md5);
      formData.append("data", packet);
      formData.append("name", name);
      formData.append("totalSize", size);
      formData.append("total", shardCount);
      formData.append("index", i + 1);

      api.Fupload(formData).then((response) => {
        console.log(response.data);
        if (response.status === 20001) {
          this.postFile(file, i + 1, md5);
        } else if (response.status === 50000) {
          setInterval(() => {
            this.postFile(file, i, md5);
          }, 2000);
        } else if (response.status === 20002) {
          this.merge(
            shardCount,
            name,
            md5,
            this.getFileType(file.name),
            file.size
          );
          console.log("上传成功");
        } else {
          console.log("未知错误");
        }
      });
    },
    merge(shardCount, fileName, md5, fileType, fileSize) {
      api
        .Fmerge({
          shardCount: shardCount,
          fileName: fileName,
          md5: md5,
          fileType: fileType,
          fileSize: fileSize,
        })
        .then((response) => {
          console.log(response.showUrls);
        });
    },
    getFileType(fileName) {
      return fileName.substr(fileName.lastIndexOf(".") + 1).toLowerCase();
    },

    removeFile(index) {
      this.uploadedFiles.splice(index, 1);
    },
    getlist() {
      api
        .zpflei({
          pageNum: 1,
          pageSize: 100,
        })
        .then((data) => {
          console.log("asdasd");
          console.log(data);
          this.roleOpts = data.list;
          console.log("asdasd");
        });
    },
    init(shopUserId) {
      console.log(shopUserId);
      this.dataForm.userId = shopUserId;
      this.visible = true;
    },
    cancell() {
      this.visible = false;
      this.dataForm = {};
      this.formData = new FormData();
      this.uploadedFiles = [];
      this.imageFile = {};
      this.videoFile = {};
      this.dataForm.workCoverUrl = null;
      this.dataForm.xworkCoverUrl = null;
      this.imageUrlzurl = null;
      this.imageUrlwurl = null;
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          this.pageLoading = true;
          console.log(this.formData);
          api.upload_minio(this.formData).then((pageVO) => {
            console.log(pageVO);
            if (pageVO) {
              console.log("***********");
              this.dataForm.workUrl = pageVO.showUrls.toString();
              api.savezp(this.dataForm).then((res) => {
                console.log("asdasd");
                console.log(res);
                console.log("asdasd");
                this.pageLoading = false;
                this.visible = false;
                this.dataForm = {};
                this.formData = new FormData();
                this.uploadedFiles = [];
                this.imageFile = {};
                this.videoFile = {};
              });
            }
          });
        }
      });
    },
  },
};
</script>
<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #130101;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  border: 1px dashed #130101;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}

.btn {
  padding: 10px;
}

.imgvideo {
  display: flex;
  flex-wrap: wrap;
}

.listss {
  padding: 10px;
  margin: 10px;
  width: 100px;
}
</style>
  